from time import sleep

import pytest
from appium import webdriver
from appium.options.android import UiAutomator2Options


def pytest_collection_modifyitems(items):
    """
    测试用例收集完成时，将收集到的用例名name和用例标识nodeid的中文信息显示在控制台上
    """
    for i in items:
        i.name = i.name.encode("utf-8").decode("unicode_escape")
        i._nodeid = i.nodeid.encode("utf-8").decode("unicode_escape")


@pytest.fixture(scope="session", autouse=True)
def init_driver():
    caps = {
        # 设置 app 安装的平台（Android，iOS）
        "platformName": "Android",
        # 设置 appium 驱动
        "appium:automationName": "uiautomator2",
        # 设置设备名称
        "appium:deviceName": "yangshuoshuo",
        # 设置被测 app 的包名、被测 app 启动页面的 Activity
        # Mac: adb logcat ActivityManager: I | grep "START"
        # Windows：adb logcat ActivityManager:I | findstr "START"
        "appium:appPackage": "hko.MyObservatory_v1_0",
        "appium:appActivity": ".AgreementPage",
        # 不清空缓存信息，保存登录信息
        "appium:noReset": True,
        # 输入中文
        "appium:unicodeKeyBoard": True,
        # 重置设备的输入键盘
        "appium:resetKeyboard": True,
        # 跳过安装，权限设置等操作
        "appium:skipDeviceInitialization": True,
        # appium:noReset为True,需要增加下面两个配置，否则app不会被调起、关闭
        "appium:forceAppLaunch": True,
        "appium:shouldTerminateApp": True
    }
    # 初始化 driver
    driver = webdriver.Remote(
        "http://127.0.0.1:4723",
        options=UiAutomator2Options().load_capabilities(caps)
    )
    # 隐式等待
    driver.implicitly_wait(20)
    sleep(5)
    yield driver
    driver.quit()